﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Routing;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Infrastructure;

namespace Xoohoo.Extensions
{
    public static class ModuleRegistryExtensions
    {
        /// <summary>
        /// 注册模块的路由配置
        /// <remarks>
        /// 后加入的模块的路由配置将排在前面，目的是提供一种"覆盖"机制
        /// </remarks>
        /// </summary>
        /// <param name="modulesLoaded"></param>
        public static void RegisterRoutes(this IModuleRegistry modulesLoaded)
        {
            IEnumerable<IModule> modules = modulesLoaded.GetModules().Reverse();

            foreach (IModule module in modules)
                module.RegisterRoutes();
        }

        /// <summary>
        /// 获取当前模块所属于的认证模块
        /// </summary>
        /// <param name="modulesLoaded"></param>
        /// <param name="currentModuleName"></param>
        /// <returns></returns>
        public static IAuthenticationModule GetAuthenticationModule(this IModuleRegistry modulesLoaded,string currentModuleName)
        {
            if (modulesLoaded == null || currentModuleName.IsNullOrWhiteSpace()) return null;

            //当前模块
            IModule currentModule = modulesLoaded.GetModules<IModule>().Where(m => m.ModuleName == currentModuleName).FirstOrDefault();
            if (currentModule == null) return null;

            //当前模块的认证模块
            IAuthenticationModule authenticationModule = modulesLoaded.GetModules<IAuthenticationModule>().Where(m => m.ModuleName == currentModule.AuthenticationModuleName).FirstOrDefault();
            return authenticationModule;
        }
    }
}
